package com.example.javascaffold.aspect;

import com.example.javascaffold.annotation.NullToEmpty;
import com.example.javascaffold.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * <p><strong>Aspect - 自动 Null 转换为 ""</strong></p>
 * <p>
 *     用在Impl实现类的方法上 <br>
 * </p>
 * <li>
 * <p>
 *     <strong>示例1: @NullToEmpty</strong> <br>
 *     结果: 会将结果中的null转换为"" <br>
 * </p>
 * </li>
 * <li>
 * <p>
 *     <strong>示例2: @NullToEmpty(result="data")</strong> <br>
 *     结果: 会将结果中叫 data 对象中的null转换为"" <br>
 * </p>
 * </li>
 * @author song
 * @see NullToEmpty
 * @since 15:25 2021/8/12
 **/
@Order(2)
@Aspect
@Slf4j
@Component
public class NullToEmptyAspect {

    @Around("@annotation(nullToEmpty)")
    public Object nullToEmpty(ProceedingJoinPoint proceedingJoinPoint, NullToEmpty nullToEmpty) throws Throwable {
        // 获取方法的执行结果
        Object proceed = proceedingJoinPoint.proceed();
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Class<?> returnType = methodSignature.getReturnType();
        // 转换Null To Empty
        if (nullToEmpty.autoNullToEmpty()) {
            return ConvertUtils.null2Empty(proceed, returnType);
        }
        return proceed;
    }

}
